package com.example.myspringbootpj.service;

import com.example.myspringbootpj.entity.TranslatedWord;
import com.example.myspringbootpj.entity.Word;
import com.example.myspringbootpj.entity.WordQuizDTO;
import com.example.myspringbootpj.mapper.WordMapper;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static org.springframework.web.servlet.function.ServerResponse.status;

@Service
public class WordService {
    private final WordMapper wordMapper;//DAO
    private final TranslationService translationService;


    private int currentOffset = 0; // 记录当前偏移量
    private final int pageSize = 20; // 每页查询的数量
    @Autowired
    public WordService(WordMapper wordMapper, TranslationService translationService) {
        this.wordMapper = wordMapper;
        this.translationService = translationService;
    }

//    //测试测试 MyBatis-Plus 是否能正常插入和生成主键：
//    public void insertWord(String wordText) {
//        Word word = new Word();
//        word.setWord_text(wordText);
//
//        wordMapper.insert(word); // 插入数据
//        System.out.println("Inserted Word ID: " + word.getWord_id()); // 输出自动生成的主键
//    }



    public List<WordQuizDTO> getWordQuiz(HttpSession session, String targetLanguage) {
        // 从 Session 获取当前用户的偏移量
        Integer currentOffset = (Integer) session.getAttribute("currentOffset");
        if (currentOffset == null) {
            currentOffset = 0; // 初始值
        }

// 查询
        int pageSize = 20;
        List<Word> words = wordMapper.getWordsWithOffset(currentOffset, pageSize);
        if (words.isEmpty()) {
            return Collections.emptyList(); // 如果没有更多单词，返回空列表
        }

// 更新偏移量
        session.setAttribute("currentOffset", currentOffset + pageSize);  // 统一使用 "currentOffset" 作为 key


        // 翻译和生成测试题
        List<TranslatedWord> translatedWords = words.stream().map(word -> {
                    String translation = translationService.translate(word.getWord_text(), targetLanguage);
                    return new TranslatedWord(word.getWord_id(), word.getWord_text(), translation);
                }).filter(translatedWord -> translatedWord.getTranslation() != null)
                .collect(Collectors.toList());

        return translatedWords.stream().map(word -> {

            // 生成选项，包含正确答案和干扰项
            List<String> options = generateOptions(word.getTranslation(), translatedWords);

            return new WordQuizDTO(word.getWordId(), word.getWordText(), word.getTranslation(), options);
        }).collect(Collectors.toList());
    }


    //        //检查每个单词是否有效
//        List<Word> validWords = words.stream()
//                .filter(word -> word != null && word.getWord_text() != null)
//                .collect(Collectors.toList());
//        if (validWords.isEmpty()) {
//            System.out.println("No valid words found.");
//            return Collections.emptyList();
//        }

    // 生成选项（包含正确答案和干扰项）
    private List<String> generateOptions(String correctAnswer, List<TranslatedWord> allWords) {
        List<String> options = allWords.stream()
                .filter(word->word!=null&&word.getTranslation()!=null)//限制条件
                .map(TranslatedWord::getTranslation) // 获取翻译
                .filter(translation -> !translation.equals(correctAnswer)) // 过滤正确答案
                .limit(3) // 限制为三个干扰项
                .collect(Collectors.toList());

        // 加入正确答案
        options.add(correctAnswer);

        // 打乱选项顺序
        Collections.shuffle(options);

        return options;
    }


    //获取收藏的单词
    public ResponseEntity<List<TranslatedWord>> getCollectionWord(HttpSession session,String targetLanguage) {
        String userId = (String) session.getAttribute("userID");
        if (userId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null); // 返回空内容，表示未登录
        }
        List<Word> words = wordMapper.getCollection(userId);


        List<TranslatedWord> translatedWords = words.stream()

                .filter(word -> word.getWord_id() != null) // 过滤掉 word_id为null
                .map(word -> {
                    String translation = translationService.translate(word.getWord_text(), targetLanguage);
                    return new TranslatedWord(word.getWord_id(), word.getWord_text(), translation);
                })
                .filter(translatedWord -> translatedWord.getTranslation() != null) // 过滤翻译失败的单词
                .toList();
        if (translatedWords.isEmpty()) {
            return ResponseEntity.ok().body(Collections.emptyList()); // 返回空列表
        }

        // 返回翻译的单词
        // 返回包含word_text和翻译的数组
        return ResponseEntity.ok().body(translatedWords);
    }

}

//    public List<Word> getWordsWithTranslation(String result) {
//        //定义list
//        List<Word> words = wordMapper.selectWordById("10");
//
//
//        //调用翻译服务，翻译单词
//      return words.stream().map(word -> {
//          String translation = translationService.translate(word.getWord_text(), result);
//          word.setWord_text(translation);
//          return word;
//      }).collect(Collectors.toList());//stream形式转list形式
//    }
//
